package com.lap.i18n.starter.autoconfigure;

import java.util.Locale;

import com.lap.i18n.starter.interceptor.I18nInterceptor;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;
import com.lap.i18n.starter.tools.Constant;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@ConditionalOnWebApplication
@AutoConfiguration
public class LangAutoConfiguration implements WebMvcConfigurer {

  @Bean
  LocaleResolver localeResolver() {
    SessionLocaleResolver localeResolver = new SessionLocaleResolver();
    localeResolver.setDefaultLocale(Locale.SIMPLIFIED_CHINESE);

    log.info("Initializer i18n framework localeResolver,{}", localeResolver);
    return localeResolver;
  }

  @Bean
  @ConditionalOnMissingBean
  LocaleChangeInterceptor localeChangeInterceptor() {
    LocaleChangeInterceptor localeInterceptor = new LocaleChangeInterceptor();
    localeInterceptor.setParamName(Constant.LANG);

    log.info("Initializer i18n framework localeChangeInterceptor,{}", localeInterceptor);
    return localeInterceptor;
  }

  @Bean
  I18nInterceptor i18nInterceptor() {
    log.info("Initializer i18n framework locale i18nInterceptor");
    return new I18nInterceptor();
  }

  @Override
  public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(localeChangeInterceptor());
    registry.addInterceptor(i18nInterceptor());
  }
}
